package com.rules.admin.service.impl;


import com.google.common.collect.Maps;
import com.rules.admin.domain.ITable;
import com.rules.admin.domain.IUser;
import com.rules.admin.entity.SysResource;
import com.rules.admin.entity.User;
import com.rules.admin.service.UserService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService, InitializingBean {
   @Autowired
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplate;

   public IUser findByUsername(String username) {
      User user = (User)this.jdbcTemplate.queryForObject("SELECT * FROM sys_user WHERE USERNAME = ?", BeanPropertyRowMapper.newInstance(User.class), new Object[]{username});
      String listSql = " select DISTINCT t3.url,t3.RESOURCE_NAME FROM sys_resource t3 LEFT JOIN (SELECT t1.resource_id FROM sys_group_role_resource t1 LEFT JOIN (select concat(GROUP_CODE,',',ROLE_CODE)as group_role_code from sys_group_user_role a left join sys_group b on a.group_id = b.ID left join sys_role c on a.role_id =  c.ID \nwhere a.user_id=" + user.getId() + ")t2 on t1.GROUP_ROLE_CODE=t2.group_role_code WHERE t1.GROUP_ROLE_CODE=t2.group_role_code)t4 on t3.RESOURCE_ID=t4.resource_id WHERE t3.RESOURCE_ID=t4.resource_id";
      List result = this.jdbcTemplate.query(listSql, new RowMapper<SysResource>() {
         public SysResource mapRow(ResultSet rs, int rowNum) throws SQLException {
            SysResource sysResource = new SysResource();
            sysResource.setUrl(rs.getString("url"));
            sysResource.setResourceName(rs.getString("resource_name"));
            return sysResource;
         }
      });
      user.setHasPermissionUrlPatterns(result);
      return user;
   }

   public void afterPropertiesSet() throws Exception {
      this.jdbcTemplate = new JdbcTemplate(this.dataSource);
   }

   public List<String> getAnonymousPermissionUrlPatterns() {
      return this.jdbcTemplate.queryForList("SELECT URL  FROM sys_resource WHERE RESOURCE_ID IN (SELECT RESOURCE_ID FROM sys_role_resource WHERE ROLE_ID = ?)", String.class, new Object[]{"ba98c88eb2f14632948d189cd41e4518"});
   }

   public Collection<ITable> getAnonymousDataPermissionTables() {
      Map<String, ITable> tablesMap = Maps.newHashMap();
      return tablesMap.values();
   }
}
